package connect4client.commands;

import messages.UserLoggedInMessage;
import connect4client.net.ConnectionController;
import connect4client.user.User;

/**
 * The UserLoggedIn command.
 * 
 * This command will handle UserLoggedIn messages.
 */
public class UserLoggedInCommand extends Command {

	public UserLoggedInCommand(UserLoggedInMessage userLoggedInCommand) {
		super(userLoggedInCommand);
	}


	@Override
	public void execute() {
		UserLoggedInMessage message = (UserLoggedInMessage) this.message;

		User me = controller.getUser();

		if (me.getLogin().equals(message.getPlayer().getLogin())) {

			// Sometimes (especially with RMI), the client received the
			// UserLoggedInMessage BEFORE the ConnectionController.login()
			// returns! So, we try to acquire this semaphore before continuing.
			try {
				ConnectionController.loginMutex.acquire();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			boolean wasLoggedIn = me.isLoggedIn();

			me.setLoggedIn(true);
			me.setLogin(message.getPlayer().getLogin());
			me.setRanking(message.getPlayer().getRanking());
			me.setRole(message.getPlayer().getRole());

			if (!wasLoggedIn) {
				guiMediator.loginSuccessful();
			}

			guiMediator.sendListPlayersMessage(false);
			guiMediator.sendListGamesMessage();

		} else {
			controller.getPlayerManager().addPlayer(message.getPlayer().getLogin(), message.getPlayer());
			guiMediator.userLoggedIn(message.getPlayer());
		}
	}
}
